package com.cxh.util;


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

public class HttpClientUtil {
	public static final Log logger = LogFactory.getLog("httpclient");


	public static String httpReader(String url, String code){
		logger.info("GetPage:"+url);
		
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod(url);	
		
		String result = null;
		try {
			client.executeMethod(method);
			int status = method.getStatusCode();
			if (status == HttpStatus.SC_OK) {
				result = method.getResponseBodyAsString();
			} else {
				logger.info("Method failed: " + method.getStatusLine());
			}
		} catch (HttpException e) {
			// 发生致命的异常，可能是协议不对或者返回的内容有问题
			logger.info("Please check your provided http address!");
			e.printStackTrace();
		} catch (IOException e) {
			// 发生网络异常
			logger.info("发生网络异常！");
			e.printStackTrace();
		} finally{
			// 释放连接
			if(method!=null)method.releaseConnection();
			method = null;
			client = null;
		}
		return result;
	}
	
	public static String httpPost(String url, Map<String, String> paramMap, String code) {
		logger.info("GetPage:"+url);
		String content = null;
		if (url == null || url.trim().length() == 0 || paramMap == null
				|| paramMap.isEmpty())
			return null;
		HttpClient httpClient = new HttpClient();
		//设置header
		httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT,"Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.2) Gecko/20090803 Fedora/3.5.2-2.fc11 Firefox/3.5.2");//
		
		//代理设置
		//httpClient.getHostConfiguration().setProxy("128.128.176.74", 808);
		
		PostMethod method = new PostMethod(url);
		Iterator<String> it = paramMap.keySet().iterator();
		

		while (it.hasNext()) {
			String key = it.next() + "";
			Object o = paramMap.get(key);
			if (o != null && o instanceof String) {
				method.addParameter(new NameValuePair(key, o.toString()));
			}
			if (o != null && o instanceof String[]) {
				String[] s = (String[]) o;
				if (s != null)
					for (int i = 0; i < s.length; i++) {
						method.addParameter(new NameValuePair(key, s[i]));
					}
			}
		}
		try {
			
			int statusCode = httpClient.executeMethod(method);
			
			System.out.println("httpClientUtils::statusCode="+statusCode);

			logger.info(method.getStatusLine());
			content = new String(method.getResponseBody(), code);
			
		} catch (Exception e) {
			logger.info("time out");
			e.printStackTrace();
		} finally {
			if(method!=null)method.releaseConnection();
			method = null;
			httpClient = null;
		}
		return content;

	}

	public static String httpPost(String url, Map<String, String> paramMap) {
		//编码：GB2312
		return HttpClientUtil.httpPost(url, paramMap, "UTF-8");
	}
	
	public static int httpPost(String url){
		int status=-1;
	    /** post方式 */
	    HttpClient client = new HttpClient();
	    PostMethod postMethod = new PostMethod(url); 
		try {
		    // 参数设置
		    postMethod.setParameter("", "");
		    // 执行postMethod
		    client.getParams().setParameter(
		            HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
		    // 执行并返回状态
		    status = client.executeMethod(postMethod);
		} catch (Exception e) {
			logger.info("发生网络异常！");
		    e.printStackTrace();
		}finally{
			// 释放连接
			if(postMethod!=null)postMethod.releaseConnection();
			postMethod = null;
			client = null;
		}
		return status;
	}
	
	    /**
	     * @作用 使用urlconnection
	     * @param url
	     * @param Params
	     * @return
	     * @throws IOException
	     */
	    public static String sendPost(String url,String Params)throws IOException{
	        OutputStreamWriter out = null;
	        BufferedReader reader = null;
	        String response="";
	        try {
	            URL httpUrl = null; //HTTP URL类 用这个类来创建连接
	            //创建URL
	            httpUrl = new URL(url);
	            //建立连接
	            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
	            conn.setRequestMethod("POST");
	            conn.setRequestProperty("Content-Type", "application/json");
	            conn.setRequestProperty("connection", "keep-alive");
	            conn.setUseCaches(false);//设置不要缓存
	            conn.setInstanceFollowRedirects(true);
	            conn.setDoOutput(true);
	            conn.setDoInput(true);
	            conn.connect();
	            //POST请求
	            out = new OutputStreamWriter(
	                    conn.getOutputStream());
	            out.write(Params);
	            out.flush();
	            //读取响应
	            reader = new BufferedReader(new InputStreamReader(
	                    conn.getInputStream()));
	            String lines;
	            while ((lines = reader.readLine()) != null) {
	                lines = new String(lines.getBytes(), "utf-8");
	                response+=lines;
	            }
	            reader.close();
	            // 断开连接
	            conn.disconnect();

	            System.out.println(response.toString());
	        } catch (Exception e) {
	        System.out.println("发送 POST 请求出现异常！"+e);
	        e.printStackTrace();
	        }
	        //使用finally块来关闭输出流、输入流
	        finally{
	        try{
	            if(out!=null){
	                out.close();
	            }
	            if(reader!=null){
	                reader.close();
	            }
	        }
	        catch(IOException ex){
	            ex.printStackTrace();
	        }
	    }
	        return response;
	}
	    
	    public static String sendGet(String url) {
			String line = "";
			PrintWriter out = null;

			BufferedReader in = null;
			try {
				URL realUrl = new URL(url);

				HttpURLConnection conn = (HttpURLConnection) realUrl
						.openConnection();

				conn.setRequestProperty("accept", "*/*");
				conn.setRequestProperty("connection", "Keep-Alive");
				conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				conn.setRequestProperty("user-agent", "Mozilla/5.0 (Linux; Android 6.0; 1503-M02 Build/MRA58K) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile MQQBrowser/6.2 TBS/036558 Safari/537.36 micromessage/6.3.25.861 NetType/WIFI Language/zh_CN");
				/*conn.setRequestProperty("user-agent",
						"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");*/
				//conn.set
				//conn.setDoOutput(true);
				conn.setDoInput(true);
				conn.setRequestMethod("GET");
				conn.connect();

				//out = new PrintWriter(conn.getOutputStream());

				//out.print(param);

				//out.flush();

				int code = conn.getResponseCode();
				InputStream is = null;
				if (code == 200)
					is = conn.getInputStream();
				else {
					is = conn.getErrorStream();
				}
				in = new BufferedReader(new InputStreamReader(is));

				String result = null;
				while ((result = in.readLine()) != null) {
					line = line + result;
				}
				//line = new String(line.getBytes("gbk"), "utf-8");
			} catch (Exception e) {
				System.out.println("发送 GET 请求出现异常！" + e);
				e.printStackTrace();
				
			} finally {
				try {
					if (out != null) {
						out.close();
					}
					if (in != null)
						in.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
			return line.toString();
		}
}
